﻿using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using Winton.Extensions.Configuration.Consul;

namespace Bridge.WorkflowService.Host.Startup
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        internal static IHostBuilder CreateHostBuilder(string[] args) =>
            Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    #region 动态加载配置中心的配置文件

                    // 1、动态加载配置中心的配置文件
                    webBuilder.ConfigureAppConfiguration((hostingContext, config) =>
                    {
                        // 加载默认配置信息到Configuration
                        hostingContext.Configuration = config.Build();

                        var isEnableConsul = hostingContext.Configuration.GetValue<bool>("Consul:IsEnable");
                        if (!isEnableConsul)
                        {
                            return;
                        }
                        // 加载consul配置中心配置
                        var consulUrl = hostingContext.Configuration["Consul:ConsulDiscoverAddress"];
                        // 动态加载环境信息，主要在于动态获取服务名称和环境名称
                        var env = hostingContext.HostingEnvironment;
                        var currentEnvironment = env.EnvironmentName.ToLower();
                        config.AddConsul(
                            $"oms/workflow/appsettings.{currentEnvironment}.json",
                            options =>
                            {
                                options.ConsulConfigurationOptions = cco =>
                                {
                                    cco.Address = new Uri(consulUrl);
                                }; // 1、consul地址
                                options.Optional = true; // 2、配置选项
                                options.ReloadOnChange = true; // 3、配置文件更新后重新加载
                                options.OnLoadException = exceptionContext =>
                                {
                                    exceptionContext.Ignore = true;
                                }; // 4、忽略异常
                            }
                        );


                        // consul中加载的配置信息加载到Configuration对象，然后通过Configuration 对象加载项目中
                        hostingContext.Configuration = config.Build();
                    });

                    #endregion

                    webBuilder.UseUrls("http://*:8083");
                    webBuilder.UseStartup<Startup>();
                })
                .UseAutofac()
                .UseSerilog((context, logger) =>
                {
                    logger.ReadFrom.Configuration(context.Configuration);
                    logger.Enrich.FromLogContext();
                });
    }
}
